package worktime.yft.demo.Controller;

import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import worktime.yft.demo.Bean.RecordBean;
import worktime.yft.demo.Service.ProjectService;
import worktime.yft.demo.Service.RecordService;

import java.text.ParseException;
import java.util.List;

@RestController
@CrossOrigin
public class RecordController {
    @Autowired
    private RecordService recordService;
    @Autowired
    private ProjectService projectService;

    @RequestMapping("insertRecord")
    public boolean InsertRecord(RecordBean record){
        try {
            List<Integer> projects = projectService.findAllProjectId();
            for (int i = 0; i < projects.size(); i++) {
                for(int j=0;j<7;j++) {
                    if (record.getEffort()[i*7+j] > 0) {
                        recordService.insert(projects.get(i), record.getName(),record.getTime()[j], record.getEffort()[i*7+j],record.getWeeks());
                    }
                    else{
                        recordService.delete(projects.get(i), record.getName(),record.getTime()[j]);
                    }
                }
            }
            return true;
        }catch (Exception e){
            System.out.println(e);
            return false;
        }
    }

    @RequestMapping("findRecord")
    public JSONObject findRecord(String userId,String startTime,String endTime){
        return recordService.findRecordByUser(userId,startTime,endTime);
    }

    @RequestMapping("findRecordByProject")
    public JSONObject findRecordByProject(String projectName,String startTime,String endTime,String department,boolean isMonth) throws ParseException {
        if(isMonth)
            return recordService.findRecordByProject(startTime,endTime,projectService.findProjectByName(projectName).getProjectId(),department);
        else
            return recordService.findRecordByProjectWeeks(startTime,endTime,projectService.findProjectByName(projectName).getProjectId(),department);
    }

    @RequestMapping("findRecordByUser")
    public JSONObject findRecordByUser(String UserId,String startTime,String endTime,boolean isMonth) throws ParseException {
        if(isMonth)
            return recordService.findRecordByUserMon(UserId, startTime,endTime);
        else
            return recordService.findRecordByUserWeeks(UserId,startTime,endTime);
    }
}
